<template>
    <el-upload class="avatar-uploader" :action="imgUrl" :show-file-list="false" method="post" accept="file"
        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :data="data" :limit="limit"
        :headers="headers">
        <img v-if="imageUrl" :src="props.picture != '' ? props.picture : imageUrl" class="avatar" />
        <el-icon v-if="!imageUrl || props.picture != ''" class="avatar-uploader-icon">
            <Plus />
        </el-icon>
    </el-upload>
</template>
<script lang="ts" setup>
import { uploadFileApi } from '/@/api/publicApi'
import { getCurrentInstance, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, UploadProps } from 'element-plus'
import { Session } from '/@/utils/storage';
const props = defineProps({
    picture: String,
})
const emit = defineEmits(['upload'])
const { proxy } = getCurrentInstance() as any;
const imgUrl = ref(`${proxy.$uploadFile}/user/upload/uploadFile`)
const userInfo = Session.get('token')
const token = userInfo ? userInfo : '';
const headers = ref({
    "Content-Type": "multipart/form-data",
    "Api-User-Token": token
})
const limit = ref(1)
const imageUrl = ref("")
const data = ref({ type: 13, file: imageUrl.value })
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    emit("upload", imageUrl.value)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}
</script>
<style scoped lang='scss'>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 84px;
    height: 84px;
    text-align: center;
}
</style>